const { exec } = require("child_process");
const iconv = require("iconv-lite");

const removedStr = "log";

let reDict = {
  1: [RegExp(`\\.console\\.(${removedStr})\\(\\)`, "g"), ""],
  2: [RegExp(`\\.console\\.(${removedStr})\\(`, "g"), ";("],
  3: [RegExp(`console\\.(${removedStr})\\(\\)`, "g"), ""],
  4: [RegExp(`console\\.(${removedStr})\\(`, "g"), "("]
};

function hasConsole(str) {
  if (!str) {
    return false;
  }
  return Object.keys(reDict).some((i) => reDict[i][0].test(str));
}
function replaceStr(str) {
  let outputContent = str;
  Object.keys(reDict).forEach((i) => {
    let [re, s] = reDict[i];
    outputContent = outputContent.replace(re, s);
  });
  return outputContent;
}

module.exports = async function (source) {
  if (this._module.resource.includes("?")) {
    return source
  }
  const authors = this.query ? this.query.authors || [] : [];
  const arr = source.split("\n");
  for (let i = 0; i < arr.length; i++) {
    if (hasConsole(arr[i])) {
      let author
      const res = await new Promise((resolve, reject) => {
        exec(`git blame -L ${i + 1} ${this._module.resource}`, { maxBuffer: 5000 * 1024 }, function (err, stdout) {
          if (err) {
            resolve(false)
            return
          }
          // const out = iconv.decode(stdout, "cp936").split('\n')[0];
          const out = stdout.split('\n')[0];
          if (!out) {
            resolve(false)
            return
          }
          author = (out.split(" ").find(t => t.startsWith("(")) || "").slice(1);
          resolve([...authors, "Not"].includes(author))
        });
      })
      if (!res) {
        console.log(`文件${this._module.resource}，第${i + 1}行，提交人 ${author}，移除console.log`)
        arr[i] = replaceStr(arr[i])
      }
    }
  }

  return arr.join("\n");
};